<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        const str = 'aabaaeaabaaf'
        const str2 = 'aabaaf'
        function solution(str2) {
            let j = 0;
            let next = []
            next[0] = j
            for (let i = 1; i < str2.length; i++) {
                // j回退
                while (j > 0 && str2[i] !== str2[j]) {
                    j = next[j - 1]
                    next[i] = j
                }
                if (str2[i] === str2[j]) {
                    j++
                    next[i] = j
                }
            }

            return next
        }
        console.log(solution(str2))
    </script>
</body>

</html>